/****************************************************************************
 * 2025.4 小管
 ****************************************************************************/

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using QFramework;
using QAssetBundle;
using UnityEngine.U2D;

namespace ProjectSurviver
{
	public partial class ExpUpgradePanel : UIElement, IController
	{
		private ResLoader mResLoader;

		private void Awake()
		{
			mResLoader = ResLoader.Allocate();
			var iconAtlas = mResLoader.LoadSync<SpriteAtlas>("icon");
			var expUpgradeSystem = this.GetSystem<ExpUpgradeSystem>();
			foreach (var expUpgradeItem in expUpgradeSystem.Items)
			{
				BtnExpUpgradeItemTemplate.InstantiateWithParent(UpgradeRoot)
				.Self(self =>
				{
					var itemCache = expUpgradeItem;
					self.transform.Find("Icon").GetComponent<Image>().sprite = iconAtlas.GetSprite(itemCache.IconName); // 设置图标
					self.onClick.AddListener(() =>
					{
						Time.timeScale = 1.0f;
						itemCache.Upgrade();	// 升级
						this.Hide();
						AudioKit.PlaySound(Sfx.ABILITYLEVELUP);
					});
					var selfCache = self;

					itemCache.Visible.RegisterWithInitValue(visible =>
					{
						if(visible)
						{
							self.GetComponentInChildren<Text>().text = expUpgradeItem.Description;
							selfCache.Show();
							var pairedUpgradeName = selfCache.transform.Find("PairedUpgradeName");
							if(expUpgradeSystem.Pairs.TryGetValue(itemCache.Key, out var pairedName))
							{
								var pairedItem = expUpgradeSystem.Dictionary[pairedName]; // 找到对应的升级项

								if(pairedItem.CurrentLevel.Value > 0 && itemCache.CurrentLevel.Value == 0) // 只有当升级项的当前等级大于0且当前项的当前等级为0时，才显示配对项的名称
								{
									pairedUpgradeName.Find("Icon").GetComponent<Image>().sprite = 
									iconAtlas.GetSprite(pairedItem.IconName); // 设置配对项的图标
									pairedUpgradeName.Show();
								}
								else
								{
									pairedUpgradeName.Hide();
								}
							}
							else
							{
								pairedUpgradeName.Hide();
							}
						}
						else
						{
							selfCache.Hide();
						}
					}).UnRegisterWhenGameObjectDestroyed(selfCache);

					itemCache.CurrentLevel.RegisterWithInitValue(lv =>
					{
						selfCache.GetComponentInChildren<Text>().text = expUpgradeItem.Description;
					}).UnRegisterWhenGameObjectDestroyed(gameObject); 	// 确保在销毁时取消注册
				});
			}
		}

		protected override void OnBeforeDestroy()
		{
			mResLoader.Recycle2Cache(); // 回收资源加载器
			mResLoader = null;
		}

        public IArchitecture GetArchitecture()
        {
            return Global.Interface; // 返回全局的架构接口
        }
    }
}